<template>
  <el-card>
    <el-form :inline="true" :model="formInline" style="display: flex">
      <el-form-item>
        <el-input v-model="formInline.type" placeholder="字典类型" />
      </el-form-item>
      <el-form-item style="width: 100px">
        <el-select v-model="formInline.status" clearable placeholder="状态">
          <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item style="flex:1">
        <el-date-picker
            v-model="during"
            type="daterange"
            range-separator="到"
            start-placeholder="创建开始时间"
            end-placeholder="创建结束时间"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchDictionary()">查询</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card>
    <el-button type="primary" @click="showAddModal" v-if="formInline.parentId===0">添加字典</el-button>
    <el-button type="primary" @click="showAddKeyValueModal" v-if="formInline.parentId!==0">添加键值</el-button>
    <el-button type="primary" @click="showUploadModal">数据导入</el-button>
    <el-button type="primary" @click="exportData">数据导出</el-button>
    <el-popconfirm title="确认删除?" @confirm="batchDeleteDictionary">
      <template #reference>
        <el-button type="danger">批量删除</el-button>
      </template>
    </el-popconfirm>
    <el-button type="primary" @click="toAddModal" v-if="formInline.parentId!==0">返回</el-button>
    <el-table :data="dictionaries" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="ID" width="100"></el-table-column>
      <el-table-column prop="name" label="字典名称" align="center" v-if="formInline.parentId===0"></el-table-column>
      <el-table-column prop="type" label="字典类型" align="center" v-if="formInline.parentId===0">
        <template #default="{ row }">
          <el-button type="primary" link  @click="getKeyValue(row.id)">{{row.type}}</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="key" label="键" align="center" v-if="formInline.parentId!==0"></el-table-column>
      <el-table-column prop="value" label="值" align="center" v-if="formInline.parentId!==0"></el-table-column>
      <el-table-column align="center" prop="createTime" label="创建时间"></el-table-column>
      <el-table-column align="center" prop="updateTime" label="更新时间"></el-table-column>
      <el-table-column align="center" prop="status" label="状态">
        <template #default="{ row }">
          <el-radio-group v-model="row.status" is-button size="small" @change="updateDictionaryStatus(row)">
            <el-radio-button :label="i.label" :value="i.value" v-for="i in options"/>
          </el-radio-group>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="showEditModal(row)">编辑</el-button>
          <el-popconfirm title="确认删除?" @confirm="deleteDictionary(row.id)">
            <template #reference>
              <el-button type="danger" size="small">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100, 1000, 5000]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </el-card>

  <!-- 添加字典模态框 -->
  <el-dialog v-model="addDialogVisible" title="添加字典">
    <el-form ref="addFormRef" :model="addFormData" label-width="80px" :rules="rules">
      <el-form-item label="字典名称" prop="name">
        <el-input v-model="addFormData.name"></el-input>
      </el-form-item>
      <el-form-item label="字典类型" prop="type">
        <el-input v-model="addFormData.type"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addDictionary(addFormRef)">确定</el-button>
        </span>
    </template>
  </el-dialog>

  <!-- 添加键值模态框 -->
  <el-dialog v-model="addKeyValueDialogVisible" title="添加键值">
    <el-form ref="addFormRef" :model="addFormData" label-width="80px" :rules="rules">
      <el-form-item label="键" prop="key">
        <el-input v-model="addFormData.key"></el-input>
      </el-form-item>
      <el-form-item label="值" prop="value">
        <el-input v-model="addFormData.value"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
        <span class="dialog-footer">
          <el-button @click="addKeyValueDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addDictionary(addFormRef)">确定</el-button>
        </span>
    </template>
  </el-dialog>

  <!-- 导入数据 -->
  <el-dialog v-model="uploadDialogVisible" title="导入数据">
    <el-upload class="upload-demo" drag :action="uploadURL" multiple :on-success="handleUploadSuccess">
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">拖拽文件到此处或者点击上传</div>
    </el-upload>
  </el-dialog>

  <!-- 编辑字典模态框 -->
  <el-dialog v-model="editDialogVisible" title="编辑字典">
    <el-form ref="editFormRef" :model="editFormData" label-width="80px" :rules="rules">
      <el-form-item label="字典名称" prop="name">
        <el-input v-model="editFormData.name" disabled></el-input>
      </el-form-item>
      <el-form-item label="字典类型" prop="type">
        <el-input v-model="editFormData.type"></el-input>
      </el-form-item>
      <el-form-item label="状态">
        <el-radio-group v-model="editFormData.status" is-button>
          <el-radio-button :label="i.label" :value="i.value" v-for="i in options"/>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelUpdateDictionary()">取消</el-button>
          <el-button type="primary" @click="updateDictionary(editFormRef)">确定</el-button>
        </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { fetchDictionaryPage, postDictionary, putDictionary, delDictionary, batchDelDictionary, exportDictionaryData} from "@/api/DictionaryApi.ts";
import type { ElMessage, UploadProps, FormInstance, FormRules } from 'element-plus';
import { UploadFilled } from "@element-plus/icons-vue";

interface Dictionary {
  id: number;
  name: string;
  type: string;
  key: string;
  value: string;
  description: string;
  parentId: number;
  createUser: string;
  updateUser: string;
  createTime: string;
  updateTime: string;
  status: string;
}

const dictionaries: Dictionary[] = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const addDialogVisible = ref(false);
const addKeyValueDialogVisible = ref(false);
const editDialogVisible = ref(false);
let addFormData: Dictionary = reactive({});
let editFormData: Dictionary = reactive({});
const multipleSelection = ref<Dictionary[]>([]);
const uploadDialogVisible = ref(false);
const uploadURL = ref(import.meta.env.VITE_APP_BASE_FILE_API);

const addFormRef = ref<FormInstance>();
const editFormRef = ref<FormInstance>();

const rules = reactive<FormRules>({
  name: [
    { required: true, trigger: 'blur' },
    { min: 1, max: 100, message: '字数必须为 1 到 100', trigger: 'blur', informType: 'warning' },
  ],
  type: [
    { required: true, trigger: 'blur' },
    { min: 1, max: 100, message: '字数必须为 1 到 100', trigger: 'blur', informType: 'warning' },
  ]
});

const formInline: Dictionary = reactive({
  parentId: 0
});

const during = ref([])


const options = ref([
  { value: '1', label: '正常' },
  { value: '0', label: '禁用' }
]);

const fetchDictionary = async () => {
  const response = await fetchDictionaryPage(currentPage.value, pageSize.value, formInline, during.value);
  dictionaries.value = response.data.records;
  total.value = response.data.total;
};

const addDictionary = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid) => {
    if (!valid) {
      return;
    }
    addFormData.parentId = formInline.parentId;
    const res = await postDictionary(addFormData);
    if (res.code === 200){
      addDialogVisible.value = false;
      addKeyValueDialogVisible.value = false;
      await fetchDictionary();
    }
  });
};

const cancelUpdateDictionary = () => {
  editDialogVisible.value = false;
  fetchDictionary();
};

const updateDictionary = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid) => {
    if (!valid) {
      return;
    }
    await putDictionary(editFormData);
    editDialogVisible.value = false;
    await fetchDictionary();
  });
};

const updateDictionaryStatus = async (dictionary: Dictionary) => {
  await putDictionary(dictionary);
  editDialogVisible.value = false
  await fetchDictionary();
};

const deleteDictionary = async (id: number) => {
  await delDictionary(id);
  await fetchDictionary();
};

const showAddModal = () => {
  addFormRef.value?.resetFields();
  addDialogVisible.value = true;
};

const showAddKeyValueModal = () =>{
  addFormRef.value?.resetFields();
  addKeyValueDialogVisible.value = true;
}

const showEditModal = async (row: any) => {
  editFormData = row;
  editFormRef.value?.clearValidate();
  editDialogVisible.value = true;
};

const handleCurrentChange = (newPage: number) => {
  currentPage.value = newPage;
  fetchDictionary();
};

const handleSizeChange = (newSize: number) => {
  pageSize.value = newSize;
  fetchDictionary();
};

// 多选
const handleSelectionChange = (val: Dictionary[]) => {
  multipleSelection.value = val;
}

// 批量删除
const batchDeleteDictionary = async () => {
  let ids: number[] = multipleSelection.value.map((dictionary: Dictionary) => dictionary.id);
  if (ids.length === 0) {
    return ElMessage.error("请先选中！");
  }
  await batchDelDictionary(ids);
  await fetchDictionary();
}

// 数据导入
const showUploadModal = () => {
  uploadDialogVisible.value = true;
}
const handleUploadSuccess: UploadProps['onSuccess'] = () => {
  ElMessage.success("导入成功");
  uploadDialogVisible.value = false;
  fetchDictionary();
}

// 导出数据
const exportData = async () => {
  const res = await exportDictionaryData();
  const blob = new Blob([res.data]);
  let url = window.URL.createObjectURL(blob);
  let link = document.createElement("a");
  link.href = url;
  link.setAttribute('download', formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss') + ".csv");
  document.body.appendChild(link);
  link.click();
}


const getKeyValue = async (id: Number) =>{
  formInline.parentId = id;
  const response = await fetchDictionaryPage(currentPage.value, pageSize.value, {parentId: id}, []);
  dictionaries.value = response.data.records;
  total.value = response.data.total;
}

const toAddModal=()=>{
  formInline.parentId = 0;
  fetchDictionary()
}

fetchDictionary();

</script>

<style scoped>
.el-card {
  margin-top: 20px;
  border: 1px solid rgba(0, 0, 0, 0.2);
  box-shadow: 0 0 0 #ffffff;
  outline: 0;
}
</style>
